package com.daguchuangyi.erp_android.login;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.base.TransStatusBarActivity;
import com.daguchuangyi.erp_android.manager.NetworkManager;
import com.daguchuangyi.erp_android.manager.ParameterManager;
import com.daguchuangyi.erp_android.manager.UserInfoManager;
import com.daguchuangyi.erp_android.manager.networkservice.AccountService;
import com.daguchuangyi.erp_android.productlist.ProductSummaryManager;
import com.daguchuangyi.erp_android.productlist.ProductionSummaryActivity;
import com.daguchuangyi.erp_android.productlist.classifiaction.ClassificationManager;
import com.daguchuangyi.erp_android.util.ErrorHandler;
import com.daguchuangyi.erp_android.util.PermissionUtils;
import com.daguchuangyi.erp_android.util.PreferenceUtil;
import com.jude.utils.JUtils;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.net.URL;
import java.util.HashMap;
import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
import yswl.permission.PermissionListener;
import yswl.permission.PermissionUtil;

public class LoginActivity extends TransStatusBarActivity implements IPInputDialog.OnIpSelectListener {

    private static final String TAG = "LoginActivity";

    private View mNetAddressWrapper;
    private TextView mNetAddressContentTv;

    private EditText mUserNameEt;
    private EditText mPswEt;
    private CheckBox mSavePswCb;
    private TextView mLoginTv;

    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();

    static   String[] permissions = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        requestPermiss();
        initIpView();
        initAccountView();
    }

    private void requestPermiss() {
        PermissionUtil permissionUtil = new PermissionUtil(this);
        permissionUtil.requestPermissions(permissions, new PermissionListener() {
            @Override
            public void onGranted() {
                Log.e(TAG,"--------onGranted");
            }

            @Override
            public void onDenied(List<String> deniedPermission) {
                Log.e(TAG,"---------onDenied");
            }

            @Override
            public void onDeniedForever(List<String> deniedPermission) {
                Log.e(TAG,"--------onDeniedForever");
            }
        });

    }

    private void initIpView() {
        mNetAddressWrapper = findViewById(R.id.ip_edit_wrapper);
        mNetAddressContentTv = (TextView) findViewById(R.id.ip_edit_content_tv);

        mNetAddressWrapper.setOnClickListener(v -> showIpInputDialog());

        String savedIp = PreferenceUtil.getString(PreferenceUtil.TAG_IP_SAVED, "");
        if (TextUtils.isEmpty(savedIp)) {
            showIpInputDialog();
        } else {
            mNetAddressContentTv.setText(savedIp);
        }
    }

    @Override
    protected void onResume() {
//        ClassificationManager.getInstance().clear();
        super.onResume();
    }

    private void initAccountView() {
        mUserNameEt = (EditText) findViewById(R.id.user_name_edit);
        mPswEt = (EditText) findViewById(R.id.psw_edit);
        mSavePswCb = (CheckBox) findViewById(R.id.save_psw_check_box);
        mLoginTv = (TextView) findViewById(R.id.login_btn);
        mLoginTv.setOnClickListener(v -> doLogin());

        String userNameSaved = PreferenceUtil.getString(PreferenceUtil.TAG_USER_NAME, "");
        String pswSaved = PreferenceUtil.getString(PreferenceUtil.TAG_LOGIN_PSW, "");
        mUserNameEt.setText(userNameSaved);
        mPswEt.setText(pswSaved);
        mPswEt.setOnEditorActionListener((textView, actionId, keyEvent) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                doLogin();
                return true;
            }
            return false;
        });

        mSavePswCb.setChecked(PreferenceUtil.getBoolean(PreferenceUtil.TAG_SAVE_LOGIN_INFO, true));
    }

    private void doLogin() {
        ProductSummaryManager.getInstance().clear();
        ParameterManager.getInstance().clear();
        ClassificationManager.getInstance().clear();
        String userName = mUserNameEt.getText().toString().trim();
        String password = mPswEt.getText().toString();
        boolean shouldSave = mSavePswCb.isChecked();
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            JUtils.Toast("信息不完整，无法登录");
            return;
        }
        if (TextUtils.isEmpty(PreferenceUtil.getString(PreferenceUtil.TAG_IP_SAVED, ""))) {
            JUtils.Toast("未找到设置的IP地址，请检查");
            return;
        }
        if (shouldSave) {
            PreferenceUtil.save(PreferenceUtil.TAG_USER_NAME, userName);
            PreferenceUtil.save(PreferenceUtil.TAG_LOGIN_PSW, password);
            PreferenceUtil.save(PreferenceUtil.TAG_SAVE_LOGIN_INFO, true);
        }
        HashMap<String, Object> loginMap = new HashMap<>();
        loginMap.put("name", userName);
        loginMap.put("password", password);


        final KProgressHUD hubDialog = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("登录中")
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();

        Subscription loginSubscription = NetworkManager.getInstance().getRetrofit().create(AccountService.class)
                .login(loginMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(userInfoModel -> {
                    JUtils.Log("login successfully.");
                    UserInfoManager.getUserInfoManager().setUserInfoModel(userInfoModel);
                    Intent intent = new Intent(LoginActivity.this, ProductionSummaryActivity.class);
                    startActivity(intent);
                }, throwable -> {
                    JUtils.Log("login error.");
                    String msg = "登录失败，请检查IP或者账号信息";
                    ErrorHandler.handlerNetworError(throwable, msg);
                    throwable.printStackTrace();
                    hubDialog.dismiss();
                }, hubDialog::dismiss);
        mCompositeSubscription.add(loginSubscription);
    }

    private void showIpInputDialog() {
        IPInputDialog dialog = new IPInputDialog();
        dialog.setOnIpSelectListener(this);
        dialog.show(getSupportFragmentManager(), "IPInputDialog");
    }

    @Override
    public void onIpInput(String ipAddress) {
//        JUtils.Toast("input IP address is : " + ipAddress);
        JUtils.Log("ipAddress content is : " + ipAddress);
        PreferenceUtil.save(PreferenceUtil.TAG_IP_SAVED, ipAddress);
        mNetAddressContentTv.setText(PreferenceUtil.getString(PreferenceUtil.TAG_IP_SAVED, ""));
        NetworkManager.getInstance().refreshBaseUrl(ipAddress);
    }

    @Override
    public void onInputCancel() {
//        JUtils.Toast("取消输入IP地址");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeSubscription.clear();
    }
}
